<template>
  <div class="background">
    <el-container class="centered-container">
      <el-header class="header">软件造价评估系统</el-header>
      <el-main>
        <el-card class="box-card">
          <div class="logo-container">
            <img src="../picture/logo.png" alt="Logo" class="logo"/>
          </div>
          <el-tabs v-model="activeTab" type="card">
            <el-tab-pane label="登录" name="login">
              <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" @submit.native.prevent="handleLogin">
                <el-form-item prop="username">
                  <el-input
                    v-model="loginForm.username"
                    placeholder="请输入用户名"
                  >
                    <template #prefix>
                      <el-icon><User /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input
                    type="password"
                    v-model="loginForm.password"
                    show-password
                    placeholder="请输入密码"
                  >
                    <template #prefix>
                      <el-icon><Lock /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item class="captcha-item" prop="captcha">
                  <el-input
                    v-model="loginCaptcha.input"
                    placeholder="请输入验证码"
                    class="captcha-input"
                  ></el-input>
                  <canvas ref="loginCaptchaCanvas" @click.prevent="refreshCaptcha('login')" class="captcha-canvas"></canvas>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" native-type="submit" class="full-width">登录</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="注册" name="register">
              <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" @submit.native.prevent="handleRegister">
                <el-form-item prop="username">
                  <el-input
                    v-model="registerForm.username"
                    placeholder="请输入用户名"
                  >
                    <template #prefix>
                      <el-icon><User /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input
                    type="password"
                    v-model="registerForm.password"
                    show-password
                    placeholder="请输入密码"
                  >
                    <template #prefix>
                      <el-icon><Lock /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="phone">
                  <el-input
                    v-model="registerForm.phone"
                    placeholder="请输入电话"
                  >
                    <template #prefix>
                      <el-icon><Phone /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="email">
                  <el-input
                    v-model="registerForm.email"
                    placeholder="请输入邮箱"
                  >
                    <template #prefix>
                      <el-icon><Message /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="tenant">
                  <el-input
                    v-model="registerForm.tenant"
                    placeholder="请输入租户"
                  >
                    <template #prefix>
                      <el-icon><OfficeBuilding /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item prop="gender">
                  <el-radio-group v-model="registerForm.gender">
                    <el-radio label="Male">男</el-radio>
                    <el-radio label="Female">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item class="captcha-item" prop="captcha">
                  <el-input
                    v-model="registerCaptcha.input"
                    placeholder="请输入验证码"
                    class="captcha-input"
                  ></el-input>
                  <canvas ref="registerCaptchaCanvas" @click="refreshCaptcha('register')" class="captcha-canvas"></canvas>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" native-type="submit" class="full-width">注册</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { UserService } from '../api/Login';
import { ElMessage } from 'element-plus';
import { User, Lock, Phone, Message, OfficeBuilding } from '@element-plus/icons-vue';

const activeTab = ref('login');
const loginForm = ref({
  username: '',
  password: ''
});
const registerForm = ref({
  username: '',
  password: '',
  phone: '',
  email: '',
  tenant: '',
  gender: 'Male'
});
const loginCaptcha = ref({
  input: '',
  text: ''
});
const registerCaptcha = ref({
  input: '',
  text: ''
});
const router = useRouter();

const loginRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
});

const registerRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
  tenant: [
    { required: true, message: '请输入租户', trigger: 'blur' }
  ],
});

const generateCaptcha = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let captchaText = '';
  for (let i = 0; i < 4; i++) {
    captchaText += chars[Math.floor(Math.random() * chars.length)];
  }
  return captchaText;
};

const drawCaptcha = (canvas, captchaText) => {
  const ctx = canvas.getContext('2d');
  const width = canvas.width = 100;
  const height = canvas.height = 40;
  ctx.clearRect(0, 0, width, height);
  ctx.fillStyle = '#f2f2f2';
  ctx.fillRect(0, 0, width, height);
  
  ctx.font = '24px Arial';
  ctx.fillStyle = '#333';
  ctx.fillText(captchaText, 10, 30);
  
  // Add some random lines for extra security
  for (let i = 0; i < 6; i++) {
    ctx.strokeStyle = getRandomColor();
    ctx.beginPath();
    ctx.moveTo(Math.random() * width, Math.random() * height);
    ctx.lineTo(Math.random() * width, Math.random() * height);
    ctx.stroke();
  }

  // Add some random dots for extra security
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = getRandomColor();
    ctx.beginPath();
    ctx.arc(Math.random() * width, Math.random() * height, 1, 0, 2 * Math.PI);
    ctx.fill();
  }
};

const getRandomColor = () => {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
};

const refreshCaptcha = (formType) => {
  const captchaText = generateCaptcha();
  if (formType === 'login') {
    loginCaptcha.value.text = captchaText;
    drawCaptcha(loginCaptchaCanvas.value, captchaText);
  } else {
    registerCaptcha.value.text = captchaText;
    drawCaptcha(registerCaptchaCanvas.value, captchaText);
  }
};

const handleLogin = () => {
  router.push('/main/home');
  /* const formRef = loginFormRef.value;
  formRef.validate((valid) => {
    if (valid) {
      if (loginCaptcha.value.input.toLowerCase() !== loginCaptcha.value.text.toLowerCase()) {
        ElMessage.error('验证码错误');
        return;
      }
      UserService.login(loginForm.value)
        .then(response => {
          if (response.data.isOk) {
            router.push('/main/home');
            ElMessage.success(response.data.msg);  
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch(error => {
          ElMessage.error('登录失败');
        });
    } else {
      ElMessage.error('请正确填写');
    } 
  }); */
};

const handleRegister = () => {
  const formRef = registerFormRef.value;
  formRef.validate((valid) => {
    if (valid) {
      if (registerCaptcha.value.input.toLowerCase() !== registerCaptcha.value.text.toLowerCase()) {
        ElMessage.error('验证码错误');
        return;
      }
      UserService.register(registerForm.value)
        .then(response => {
          if (response.data.isOk) {
            ElMessage.success(response.data.msg);
            activeTab.value = 'login';
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch(error => {
          ElMessage.error('注册失败');
        });
    } else {
      ElMessage.error('请正确填写');
    }
  });
};

onMounted(() => {
  refreshCaptcha('login');
  refreshCaptcha('register');
});

const loginFormRef = ref(null);
const registerFormRef = ref(null);
const loginCaptchaCanvas = ref(null);
const registerCaptchaCanvas = ref(null);
</script>

<style scoped>
.background {
  background: url('../picture/background.png') no-repeat center center fixed;
  background-size: cover;
  height: 100vh;
}

.centered-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.header {
  text-align: center;
  color: #dbc0c0;
  font-size: 50px;
  margin: 10px;
  font-family: 'STXingkai', 'Xingkai SC', 'KaiTi', '楷体', 'Arial', sans-serif;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.9);
}


.box-card {
  width: 300px;
  padding: 20px;
  background-color: rgba(238, 246, 237, 0.9);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  border-radius: 8px;
  overflow: hidden; /* 隐藏滚动条 */
  white-space: nowrap; /* 防止文本换行 */
  text-overflow: ellipsis; /* 溢出时显示省略号 */
}

.logo-container {
  text-align: center;
  margin-bottom: 20px;
}

.logo {
  width: 200px;
  height: 90px;
}

.full-width {
  width: 100%;
}

.captcha-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-canvas {
  margin-left: 10px;
  cursor: pointer;
  border: 1px solid #ccc;
  height: 40px; /* 确保canvas高度一致 */
  width: 100px; /* 设置固定宽度 */
}
</style>
